package com.basic.quartz.task;

import com.basic.common.annotation.Log;
import com.basic.common.config.BasicConfig;
import com.basic.common.constant.Constants;
import com.basic.common.enums.BusinessType;
import com.basic.common.utils.DateUtils;
import com.basic.common.utils.StringUtils;
import com.basic.common.utils.file.FileUtils;
import com.basic.system.service.ISysConfigService;
import com.basic.tool.service.ISysDownloadCenterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.TimerTask;

/**
 * 定时删除下载中心生成的文件
 *
 * @author zhaoxy_jn@163.com
 */
@Component
@EnableScheduling
public class DeleteFileTask {

    Logger logger = LoggerFactory.getLogger(DeleteFileTask.class);

    @Resource
    private ISysConfigService configService;

    @Resource
    private ISysDownloadCenterService downloadCenterService;

    @Scheduled(cron = "0 0 1 * * ?")
    @Log(title = "定时删除下载中心生成的文件", businessType = BusinessType.TASK)
    public void configureTasks() {
        new TimerTask() {
            @Override
            public void run() {

                // 获取定时删除下载中心文件开关的状态
                String status = configService.selectConfigByKey("sys.download.deleteFile");
                if(StringUtils.isNotEmpty(status) && StringUtils.equals(status, "on")){
                    logger.info("删除下载中心7天前的文件: 状态-> {}, 线程名称-> {}，开始时间-> {}，", status, Thread.currentThread().getName(), DateUtils.getTime());
                    List<String> fileLists = downloadCenterService.getListFor7Days();
                    fileLists.forEach(fileUrl -> {
                        // 删除文件
                        FileUtils.deleteFile(BasicConfig.getProfile() + StringUtils.substringAfter(fileUrl, Constants.RESOURCE_PREFIX));
                    });
                } else {
                    logger.warn("删除下载中心7天前的文件: 状态-> {}", status);
                }
            }
        };
    }
}
